package com.cheetah.start.common.log;

import cn.hutool.http.useragent.UserAgent;
import cn.hutool.http.useragent.UserAgentUtil;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.NvMap;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;

/**
 * 打印所有请求的过滤器
 *
 * @author 25175
 * @date 2022/6/18 11:56
 */
@Slf4j
@Component
public class WebLogFilter implements Filter {



    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        long start = System.currentTimeMillis();

        chain.doFilter(ctx);

        String url = ctx.url();
        String method = ctx.method();
        NvMap paramMap = ctx.paramMap();
        long cost = System.currentTimeMillis() - start;
        Object result = ctx.result;
        String userAgent = ctx.userAgent();
        String contentType = ctx.contentType();
        String ip = ctx.ip();
        UserAgent agent = UserAgentUtil.parse(userAgent);
        Object controller = ctx.controller();
        if (controller != null) {
            log.info("\n┣ 接口地址:[{}]\n┣ 参数:[{}] [{}] [{}]\n┣ 耗时:[{}]ms\n┣ 设备:[{}]\n┣ IP:[{}]\n┣ 结果:[{}]",
                    url,
                    paramMap,
                    method,
                    contentType,
                    cost,
                    agent.getBrowser().getName() + "|" + agent.getVersion() + "|" + agent.getOs(),
                    ip,
                    result);
        }

    }
}
